/**
 * 
 */
package com.tmc.service.common;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.dao.impl.UserDaoImpl;
import com.tmc.entity.common.EthUser;
import com.tmc.service.cache.CacheServiceImpl;
import com.tmc.util.MD5Util;

@Service
@Transactional
public class LoginServiceImpl {

	private Log log = LogFactory.getLog(this.getClass());

	public static String cache_key_token = "cache_key_token";

	@Autowired
	private UserDaoImpl userDao;

	@Autowired
	private CacheServiceImpl cache;

	public CommonResult login(String userCode, String password) {
		try {
			EthUser user = userDao.getUser(userCode, password);
			if (user == null) {
				return CommonResult.makeFail("用户名密码错误！");
			} else {
				String token = this.cacheToken(user);
				return CommonResult.makeSuccess("登录成功！", token);
			}
		} catch (Exception e) {
			log.error(e);
		}
		return CommonResult.makeFail("系统错误！");
	}
	
	public CommonResult logout(ContextInfo context) {
		cache.remove(context.getToken());
		return CommonResult.makeSuccess();
	}

	public ContextInfo getContextInfoByToken(String token) {
		ContextInfo context = (ContextInfo) cache.get(token);
		if (context != null) {
			//继续缓存，延长token期限
			cache.put(token, context);
			return context;
		}
		return null;
	}

	public String cacheToken(EthUser user) {
		String token = MD5Util.string2MD5(user.getUserCode());
		cache.put(token, this.buildContextInfo(user, token));
		return token;
	}

	private ContextInfo buildContextInfo(EthUser user, String token) {
		ContextInfo context = new ContextInfo();
		context.setUserId(user.getUserId());
		context.setUsername(user.getUserName());
		context.setToken(token);
		context.setVipLevel(user.getVipLevel());
		return context;
	}

	public void addUser(EthUser user) {
		userDao.save(user);
	}

}
